package org.demo.controller;

import org.demo.common.Result;
import org.demo.entity.Housewear;
import org.demo.entity.Users;
import org.demo.service.IUsersService;
import org.demo.utils.JwtUtil;
import org.demo.utils.Md5Util;
import org.demo.utils.ThreadLocalUtil;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


//用户表
@RestController
@RequestMapping("/user")
public class UsersController {
    @Autowired
    private IUsersService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private static final Logger logger = LoggerFactory.getLogger(UsersController.class);
    //注册
    @PostMapping("/register")
    public Result register(@RequestParam String username,
                           @RequestParam String password,
                           @RequestParam String repassword,
                           @RequestParam String roleId) {
        // 定义正则表达式，用于匹配 5 - 16 位非空字符
        String regex = "^[\\S]{5,16}$";
        if (username.matches(regex) && password.matches(regex) && repassword.matches(regex)) {
            if (repassword.equals(password)) {
                Users u = userService.findByUserName(username);
                if (u == null) {
                    Users user = new Users();
                    user.setUsername(username);
                    user.setPassword(password);
                    user.setRoleId(roleId);
                    userService.register(user);
                    return Result.success();
                } else {
                    return Result.error("用户名已被占用");
                }
            } else {
                return Result.error("两次密码不一样");
            }
        } else {
            return Result.error("参数不合法，用户名和密码应为 5 - 16 位非空字符");
        }
    }

    @GetMapping("/listLan")
    public Result<List<Users>> listLan (@RequestBody (required = false) Users users){
        List<Users> user= userService.listLan(users);
        return Result.success(user);
    }
    @GetMapping("/listInt")
    public Result<List<Users>> listInt (@RequestBody (required = false) Users users){
        List<Users> user= userService.listInt(users);
        return Result.success(user);
    }
    @GetMapping("/listCus")
    public Result<List<Users>> listCus (@RequestBody (required = false) Users users){
        List<Users> user= userService.listCus(users);
        return Result.success(user);
    }

    //注册
    @PostMapping("/login")
    public  Result<Map> login(@RequestParam String username,
                                 @RequestParam String password,
                                 @RequestParam String roleId){
        //根据用户名查询
        Users loginUser = userService.lambdaQuery().eq(Users::getUsername,username).one();
        //判断是否存在
        if (loginUser==null){
            return Result.error("用户名错误");
        }
        if (username.equals("admin")){
            roleId="ROLE_admin";
        }
        if (loginUser.getRoleId().equals(roleId)){
            if (Md5Util.getMD5String(password).equals(loginUser.getPassword())){
                Map<String,Object> claims = new HashMap<>();
                claims.put("id",loginUser.getId());
                claims.put("username",loginUser.getUsername());
                String token = JwtUtil.genToken(claims);
                //token存储到redis中
                ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
                operations.set(token,token,1, TimeUnit.HOURS);//redis 存储1小时token
                Map suc = new HashMap<>();
                suc.put("roleId",roleId);
                suc.put("token",token);
                return Result.success(suc);
            }
        }else {
            return Result.error("未找到角色信息");
        }

        //判断密码是否正确
        return Result.error("密码错误");
    }
    //查看信息
    @GetMapping("/userInfo")
    public Result<Users> userInfo (){

        //从token中获取username
        Map<String,Object> map = ThreadLocalUtil.get();
        String username= (String) map.get("username");

        Users user = userService.findByUserName(username);
        return Result.success(user);
    }
    //查看所有
    @PostMapping("/listAll")
    public Result<List<Users>> listAll (@RequestBody (required = false) Users users){
        List<Users> user= userService.listAll(users);
        return Result.success(user);
    }
    //添加
    @PostMapping("/addUser")
    public  Result<String> addUser(@RequestBody Users user){
        userService.addUser(user);
        return Result.success("提交成功");
    }

    //修改信息
    @PostMapping("/updateUser")
    public  Result<String> updateUser(@RequestBody Users user){
        userService.updateUser(user);
        return Result.success("修改成功");
    }
    //修改头像
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }
    //重置密码
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> params,@RequestHeader("Authorization") String token){
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要的参数");
        }
        //token 里面取用户名
        Map<String,Object> map = ThreadLocalUtil.get();
        String username= (String) map.get("username");
        Users users =  userService.findByUserName(username);
        //加密输入的密码与数据库比对
        if (!Md5Util.getMD5String(oldPwd).equals(users.getPassword())){
            return Result.error("原密码填写不正确");
        }
        if (!newPwd.equals(rePwd)){
            return Result.error("两次填写的新密码不一样");
        }
        userService.updatePwd(newPwd);
        //删除redis的token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);

        return Result.success();
    }
}
